import { baseURL } from '@/utils/config'

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};
/**
* 时间戳转化为年 月 日 时 分 秒
* ts: 传入时间戳
* format：返回格式，支持自定义，但参数必须与formateArr里保持一致
*/
function formatTime(timestamp, format) {
  const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  let returnArr = [];
  let time = timestamp * 1000;
  let date = new Date(time);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  returnArr.push(year, month, day, hour, minute, second);
  returnArr = returnArr.map(formatNumber);

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }

  return format;
}

        // 上传视频
function chooseVideo(api) {
	return new Promise((resolve, reject) => {
		// uploadFile 存储需要上传的文件
		let uploadFile = ''
		// 1.选择要上传的视频
		uni.chooseVideo({
			maxDuration: 60,		// 拍摄视频最长拍摄时间，单位秒。最长支持 60 秒。
			sourceType: ['album','camera'],		// album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
			success: (result) => {
				console.log(result)
				uni.showLoading({
					mask: true,
					title: '上传中...'
				})
				
				const token = uni.getStorageSync('token');
				var that = this;
				// 2.上传所选视频到服务器
				uni.uploadFile({
					// 需要上传的地址
					url:baseURL+api,
					// filePath  需要上传的文件
					filePath: result.tempFilePath,
					name: 'file',
					header: {
						token: token		// 挂载请求头为用户的 token
					},
					success: function(res) {
						uni.hideLoading()
						if(res.statusCode == 200){
							resolve(JSON.parse(res.data))
						}
						else{
							return uni.showToast({
								title:"上传失败",
								duration: 1500,
								icon:'none'
							});
						}
					},
					error : function(e){
						return uni.showToast({
							title:"上传失败",
							duration: 1500,
							icon:'none'
						});
					},
					file: res => {
						uni.hideLoading()
					}
				});
				
				uploadTask.onProgressUpdate(function (res) {
					//_self.percent = res.progress;
					console.log('上传进度' + res.progress);
					console.log('已经上传的数据长度' + res.totalBytesSent);
					console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
				});
			},
			error : function(e){
				console.log(e);
			}
		});
	})
}

function uploadFile(api,num = 1){
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: num, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: (res) => {
				console.log("正常文件上传：",res)
				uni.showLoading({
					title: '上传中'
				});
				const token = uni.getStorageSync('token');
				const uploadTask = uni.uploadFile({
					url:baseURL+api,
					filePath:res.tempFiles[0].path,
					name: 'file',
					header: {
						'token': token
					},
					success: res => {
						uni.hideLoading()
						if(res.statusCode == 200){
							resolve(JSON.parse(res.data))
						}
						else{
							return uni.showToast({
								title:"上传失败",
								duration: 1500,
								icon:'none'
							});
						}
					},
					error : function(e){
						return uni.showToast({
							title:"上传失败",
							duration: 1500,
							icon:'none'
						});
					},
					file: res => {
						uni.hideLoading()
					}
				});
				
				uploadTask.onProgressUpdate(function (res) {
					//_self.percent = res.progress;
					console.log('上传进度' + res.progress);
					console.log('已经上传的数据长度' + res.totalBytesSent);
					console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
				});
			},
			error : function(e){
				console.log(e);
			}
		})
	})
}

// 上传多图片
function chooseImgs(api){
	return new Promise((resolve, reject) => {
		var _this = this
		uni.chooseImage({
			count:9,
			sizeType:['original', 'compressed'],
			sourceType: ['album'], //从相册选择
			success:(res) => {
				uni.showLoading({
					title: '上传中'
				});
				const tempFilePaths = res.tempFilePaths
				const token = uni.getStorageSync('token');
				for(var i=0;i<tempFilePaths.length;i++){
					const uploadTask = uni.uploadFile({
					url:baseURL+api,
						filePath:tempFilePaths[i].path,
						name: 'file',
						header: {
							'token': token
						},
						success: res => {
							if(res.statusCode == 200){
								resolve(JSON.parse(res.data))
							}
							else{
								return uni.showToast({
									title:"上传失败",
									duration: 1500,
									icon:'none'
								});
							}
						},
						error : function(e){
							return uni.showToast({
								title:"上传失败",
								duration: 1500,
								icon:'none'
							});
						},
						file: res => {
							uni.hideLoading()
						}
					});
					 
					uploadTask.onProgressUpdate(function (res) {
						//_self.percent = res.progress;
						console.log('上传进度' + res.progress);
						console.log('已经上传的数据长度' + res.totalBytesSent);
						console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
					});
				}
				uni.hideLoading()
			}
		})
	})
}
//图片预览
function previewImage(e){
	var _this = this
	var index = e.currentTarget.dataset.index;
	//所有图片
	var imgbox = _this.totalImg;
	wx.previewImage({
		//当前显示图片
		current: imgbox[index],
		//所有图片
		urls: imgbox
	})
}


//方法：用来判断是否是微信内置的浏览器
function isWechat() {
	return String(view.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}

//取值
function get(key,sync = true) {
    try {
		if(sync){
			return uni.getStorageSync(key);
		}else{
			let data = '';
			uni.getStorage({
				key:key,
				success: function (res) {
					data = res.data;
				}
			});
			return data;
		}
    } catch (e) {
        return false;
    }
}
//赋值
function set(key, value, sync = true) {
    try {
        if (sync) {
            return uni.setStorageSync(key, value);
        } else {
            uni.setStorage({
                key: key,
                data: value
            });
        }
    } catch (e) {

    }
}

//移除
function del(key, sync = true){
    try {
        if (sync) {
            return uni.removeStorageSync(key);
        } else {
            uni.removeStorage({
                key: key
            });
        }
    } catch (e) {
        return false;
    }
}

//清空
function clear(sync = true){
    try {
        if (sync) {
            return uni.clearStorageSync();
        } else {
            uni.clearStorage();
        }
    } catch (e) {
        return false;
    }
}

/**
 * @param {String} str (y-m-d h:i:s) y:年 m:月 d:日 h:时 i:分 s:秒
 */
function dateTimeStr(str){
	var date = new Date(),
	year = date.getFullYear(), //年
	month = date.getMonth() + 1, //月
	day = date.getDate(), //日
	hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(), //时
	minute = date.getMinutes() < 10 ? date.getMinutes() : date.getMinutes(), //分
	second = date.getSeconds() < 10 ? date.getSeconds() : date.getSeconds(); //秒
	month >= 1 && month <= 9 ? (month = "0" + month) : "";
	day >= 0 && day <= 9 ? (day = "0" + day) : "";
	hour >= 0 && hour <= 9 ? (hour = "0" + hour) : "";
	minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
	second >= 0 && second <= 9 ? (second = "0" + second) : "";
	if(str.indexOf('y') != -1){
		str = str.replace('y', year)
	}
	if(str.indexOf('m') != -1){
		str = str.replace('m', month)
	}
	if(str.indexOf('d') != -1){
		str = str.replace('d', day)
	}
	if(str.indexOf('h') != -1){
		str = str.replace('h', hour)
	}
	if(str.indexOf('i') != -1){
		str = str.replace('i', minute)
	}
	if(str.indexOf('s') != -1){
		str = str.replace('s', second)
	}
	return str;
}
 

//下载文件
function downLoadFile(url){
	/*var fileUrl = this.content.enclosureUrl; 
	var url =decodeURIComponent(fileUrl);//对 encodeURIComponent() 函数编码的 URI 进行解码
	var reg = new RegExp(":443");
	url = url.replace(reg,"");*/
	
	//下载文件，生成临时地址
	uni.showLoading({
		title: '下载中...',
	})
	uni.downloadFile({
		url: url, 
		success(res) {
		  //保存到本地
		  uni.saveFile({
			tempFilePath: res.tempFilePath,
			success: function (res) {
			  const savedFilePath = res.savedFilePath;
			  // 打开文件
			  uni.openDocument({
				filePath: savedFilePath,
				success: function (res) {
				  uni.hideLoading()
				},
			  });
			},
			fail: function (err) {
				uni.hideLoading();
				uni.showLoading({
					title: '保存失败',
				})
			}
		  });
		},
		fail(res) {
			uni.hideLoading();
			uni.showLoading({
				title: '下载失败',
			})
		}
	});
	
	/* downloadTask.onProgressUpdate((res) => {
		console.log('下载进度' + res.progress);
		console.log('已经下载的数据长度' + res.totalBytesWritten);
		console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
	}); */
}
export const statusColor = {
	0: '#19be6b',
	1: '#ff4949',
	2: '#2DB7F5',
	3: '#FF9900'
}

export const isObject = (val) => {
  return Object.prototype.toString.call(val) === '[object Object]'
}

export const isArray = (arr) => Object.prototype.toString.call(arr).indexOf('Array') !== -1



module.exports = {
	chooseVideo:chooseVideo,
	uploadFile:uploadFile,
	isWechat:isWechat,
	formatTime: formatTime,
	dateTimeStr: dateTimeStr,
	previewImage:previewImage,
	set: set,
	get: get,
	del: del,
	clear: clear,
	downLoadFile:downLoadFile,
};